package com.xgr.wonderful.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.easemob.EMConnectionListener;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.EasyUtils;
import com.google.gson.Gson;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.base.BasePageActivity;
import com.xgr.wonderful.adapter.ConversationAdapter;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.constant.HttpGetUrl;
import com.xgr.wonderful.db.DatabaseUtil;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.entity.SuperConversation;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.utils.Cache;
import com.xgr.wonderful.utils.HXUtils;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;

/**
 * 1. 由自己从PersonalActivity中发出对话，后再加入List中
 * 2. 收到别人人发来的消息后，加入List中
 * 一定要有remoteUser对象 
 * @author lsj
 *
 */
public class ConversationActivity extends BasePageActivity{
	
	private ActionBar mActionBar ;
	
	private ListView mListView ;
	
	private TextView mTips ;

	private List<SuperConversation> conversationList;
	private ConversationAdapter conversationAdapter;
	
	//消息提示
	private NewMsgBroadcastRecevier receiver;
	private NotificationManager mNotificationManager;
	private Notification notification ;
	
	private HttpProxy httpProxy ;
	
	@Override
	protected void setLayoutView() {
		setContentView(R.layout.activity_conversation) ;
	}

	@Override
	protected void findViews() {
		mActionBar = (ActionBar)findViewById(R.id.actionbar_conversation) ;
		mListView = (ListView) findViewById(R.id.conversation_list);
		mTips = (TextView)findViewById(R.id.conversation_tipsTv) ;
	}

	@Override
	protected void setupViews(Bundle bundle) {
		mActionBar.setTitle("私聊") ;
		mActionBar.setDisplayHomeAsUpEnabled(true) ;
		mActionBar.setHomeAction(new Action() {
			
			@Override
			public void performAction(View view) {
				finish();
			}
			@Override
			public int getDrawable() {
				return R.drawable.weix_logo_blank;
			}
		}) ;
		
		sputil.setIsNewMsg(false) ;//去掉主界面 私聊图标 的变化 
		conversationList = loadConversationWithRecentChat() ;
		if (conversationList==null || conversationList.size()==0){
			mTips.setVisibility(View.VISIBLE) ;
		}else {
			mTips.setVisibility(View.GONE) ;
		}
		conversationAdapter = new ConversationAdapter(mContext, conversationList) ;
		mListView.setAdapter(conversationAdapter) ;
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				User remoteUser = conversationAdapter.getItem(
						position).getRemoteUser();
				
//				if (remoteUser.getID().equals(LocalUserUtils.getInstance()
//						.getLocalUserID().toString())) {
//					ToastFactory.getToast(mContext, "不能和自己聊天").show() ;
//				} else {
					Intent chatIntent = new Intent();
					chatIntent.putExtra("data",remoteUser);
					chatIntent.setClass(mContext, ChatActivity.class);
					startActivity(chatIntent);
//				}
			}
		}) ;
		// 删好友等操作
		registerForContextMenu(mListView);
		//注册聊天相关的
		receiver = new NewMsgBroadcastRecevier() ;
		HXUtils.EMRegisterReceiver((Activity) mContext, receiver,
				Constant.NEW_MESSAGE_PRIORITY_MIN);
		
		//注册一个监听连接状态的listener 
	    EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		getMenuInflater().inflate(R.menu.delete_message, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		SuperConversation tobeDeleteCons = conversationAdapter
				.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
		EMConversation emConversation = tobeDeleteCons.getEmConversation();
		switch (item.getItemId()) {
		case R.id.delete_conversation:
			// 删除此会话
			EMChatManager.getInstance().deleteConversation(
					emConversation.getUserName(), emConversation.isGroup());
			DatabaseUtil.getInstance().delConversation(
					Integer.valueOf(emConversation.getUserName()));
			refresh();
			return true ;
		case R.id.clear_conversation_history:
			//这里没有delete Database中的记录
			EMChatManager.getInstance().clearConversation(emConversation.getUserName());
			refresh();
			return true ;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	public void refresh() {
		conversationList.clear();
		conversationList.addAll(loadConversationWithRecentChat());
		conversationAdapter.notifyDataSetChanged();
		if (conversationList==null || conversationList.size()==0){
			mTips.setVisibility(View.VISIBLE) ;
		}else {
			mTips.setVisibility(View.GONE) ;
		}
	}
	/**
	 * 当activity恢复的时候，onResume()方法会被调用，所以这是一个刷新的好机会。
	 */
	@Override
	public void onResume() {
		super.onResume();
		LogUtils.i(TAG, "refresh in onResume") ;
		refresh() ;
	}

	
	private List<SuperConversation> loadConversationWithRecentChat() {
		// 得到所有的会话
		Hashtable<String, EMConversation> conversations = EMChatManager
				.getInstance().getAllConversations();
		List<SuperConversation> list = new ArrayList<SuperConversation>();
		for (EMConversation conversation : conversations.values()) {
			Integer remoteUserid = Integer.valueOf(conversation.getUserName());
			// 数据库保证返回的map不会是null，但是内容有可能是空的，数据库里面的内容 是没有conversation的
			DatabaseUtil.getInstance().initConversationDao(mContext); //一定要有，目前有些不合理
			SuperConversation superConversation = DatabaseUtil.getInstance()
					.getConversationList().get(remoteUserid);
			if (superConversation != null) {
				superConversation.setEmConversation(conversation);
				list.add(superConversation);
			}
		}
		sortConversationByLastChatTime(list);
		return list;
	}
	/**
	 * 考虑了对话为空的情况 
	 * @param conversationsList
	 */
	private void sortConversationByLastChatTime(
			List<SuperConversation> conversationsList) {
		Collections.sort(conversationsList,
				new Comparator<SuperConversation>() {
					@Override
					public int compare(SuperConversation con1,
							SuperConversation con2) {
						EMMessage con2LastMsg = con2.getEmConversation()
								.getLastMessage();
						EMMessage con1LastMsg = con1.getEmConversation()
								.getLastMessage();
						if (con2LastMsg == null && con1LastMsg == null) {
							return 0;
						} else if (con2LastMsg != null && con1LastMsg == null) {
							return 1;
						} else if (con1LastMsg != null && con2LastMsg == null) {
							return -1;
						} else {
							if (con2LastMsg.getMsgTime() == con1LastMsg
									.getMsgTime()) {
								return 0;
							} else if (con2LastMsg.getMsgTime() > con1LastMsg
									.getMsgTime()) {
								return 1;
							} else {
								return -1;
							}
						}
					}
				});
	}
	
	private class NewMsgBroadcastRecevier extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			abortBroadcast();
			String username = intent.getStringExtra("from");
			String msgid = intent.getStringExtra("msgid");
			EMMessage message = EMChatManager.getInstance().getMessage(msgid);
			// 评论推送
			if (message.getBooleanAttribute(Constant.COMMENT_PUSH_BY_HX, false) == true) {
				notifyNewMessage(message) ;
				return;
			}else {
				//如果 是新的会话，如果 是已经 有的会话，实际是不用提示，但是要考虑保存信息的问题
				notifyNewMessage(message) ;
				refresh() ;// refresh list 
			}
		}
	}
	
	private class MyConnectionListener implements EMConnectionListener{
		@Override
		public void onConnected() {
		}
		@Override
		public void onDisconnected(int arg0) {
		}
	}
	
	private void notifyNewMessage (EMMessage message){
		if (!EasyUtils.isAppRunningForeground(this)){
			LogUtils.i(TAG, "app running forground") ;
			return ;
		}
		LogUtils.i(TAG, "notify");
		
		if (notification == null){
			notification = new Notification() ;
			notification.icon= R.drawable.weix_logo_blank ;
			notification.flags = Notification.FLAG_AUTO_CANCEL ;//点击后自动取消
		}
		if (mNotificationManager == null){
			mNotificationManager = (NotificationManager) getSystemService(
					Context.NOTIFICATION_SERVICE);
		}
		String from = message.getFrom() ;
		String msgid = message.getMsgId() ;
		if (message.getBooleanAttribute(Constant.COMMENT_PUSH_BY_HX, false)== true){
			//评论提醒 
			String pushStatusJson = ((TextMessageBody)message.getBody()).getMessage();
			String fromUsername = message.getStringAttribute(Constant.COMMENT_PUSH_FROM, "") ;
			LogUtils.i(TAG, "status:"+ pushStatusJson) ;
			//Cache.putCommentReceivedStatus(pushStatusJson) ;
			Status pushStatus  = null;
			try {
				pushStatus = new Gson().fromJson(pushStatusJson, Status.class) ;
				List< Status> commentReceivedStatus = Cache.getCommentRecevicedStatus() ;
				if (commentReceivedStatus!= null && commentReceivedStatus.size()!= 0){
					//已经 存在收到的评论,则要更新一下数据 
					for (Status temp : commentReceivedStatus){
						if (String.valueOf(temp.getId()).equals(String.valueOf(pushStatus.getId()))){
							commentReceivedStatus.remove(temp) ;
						}
					}
				}else {
					commentReceivedStatus = new ArrayList<Status>() ;
				}
			    commentReceivedStatus.add(pushStatus) ;
			    //保存下来
				Cache.putCommentReceivedStatus(new Gson().toJson(commentReceivedStatus)) ;
			} catch (Exception e) {}
			//intent.putExtra("data", pushStatus);//
			Intent intent = new Intent(this ,CommentReceivedActivity.class) ;
			PendingIntent pendingIntent = PendingIntent.getActivity(this , 
					Constant.NEW_COMMENT_NOTIFICATION_ID, intent, Intent.FLAG_ACTIVITY_NEW_TASK) ;
			notification.tickerText= "收到来自"+fromUsername+"的评论";
			notification.setLatestEventInfo(this, "微圈", "收到来自"+fromUsername+"的评论",pendingIntent);
			mNotificationManager.notify(Constant.NEW_COMMENT_NOTIFICATION_ID,
					notification);
			//如果是评论，要删除这条消息,以免在聊天里面显示
			EMChatManager.getInstance().getConversation(from).removeMessage(msgid) ;
		}else {
			//收到的是新的消息，此时应该先查看是否是新的聊天，如果不是，则不用再管，如果是，应该再拉取聊天用户的信息
			if (DatabaseUtil.getInstance().getConversation(Integer.valueOf(from))== null){
				String url = HttpGetUrl.GetUser() + "?id="+ from.toString();
				httpProxy = new HttpProxy() ;
				httpProxy.queryUserByUserID(url, new IHttpRequestListener() {
					
					@Override
					public void OnHttpRequestSuccessful(String result, int errCode) {
						if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
							User remoteUser = null ;
							try {
								remoteUser = new Gson().fromJson(result, User.class);
							} catch (Exception e) {}
							if (remoteUser!= null && remoteUser.getUsername()!= null){
								//下面这句应该可以不加，不清楚
								LogUtils.i(TAG, "new conversation msg push and get user info ok") ;
								DatabaseUtil.getInstance().initConversationDao(getApplicationContext()) ;
								SuperConversation superConversation = new SuperConversation(
										remoteUser.getID(), remoteUser.getUsername(),
										remoteUser.getPhoto());
								DatabaseUtil.getInstance().addConversation(
										remoteUser.getID(), superConversation);
								//刷新一下，保证列表的更新,和MainActivity中的不同
								refresh() ;
							}
						}
					}
					@Override
					public void OnHttpRequestStart() {
					
					}	
					@Override
					public void OnHttpRequestFailure(String info) {
					}
				}) ;
			}
			//原来就有的会话，直接通知就行了(上面的查询过程，是单独在一个线程进行的)
			Intent intent1 = new Intent(this, ConversationActivity.class );
			PendingIntent pendingIntent = PendingIntent.getActivity(this , 
					Constant.NEW_MESSAGE_NOTIFICATION_ID, intent1, Intent.FLAG_ACTIVITY_NEW_TASK) ;
			notification.tickerText= "收到了新的消息";
			notification.setLatestEventInfo(this, "微圈", "收到了新消息",pendingIntent);
			mNotificationManager.notify(Constant.NEW_MESSAGE_NOTIFICATION_ID,
					notification);
		}
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (receiver != null) {
			try {
				unregisterReceiver(receiver);
				receiver = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		super.onDestroy();
	}

}
